//
//  HHYWebController.m
//  云成绩
//
//  Created by 慧趣小歪 on 2017/6/19.
//  Copyright © 2017年 zj. All rights reserved.
//

#import "TWWebController.h"
#import "UIAlertMaker.h"
#import <WebKit/WebKit.h>


@interface TWWebController () <WKDelegate>
@property (nonatomic, assign) BOOL isFirstAppear;
@property (nonatomic, assign) BOOL oldNavigationHidden;
@end

@implementation TWWebController

- (void)loadView {
    self.delegate = self;
    [super loadView];
}

- (BOOL)prefersHomeIndicatorAutoHidden{
    return YES;
}

- (void)viewDidLoad {
    _isFirstAppear = YES;

    [super viewDidLoad];
    self.oldNavigationHidden = self.navigationController.navigationBar.hidden;
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back-1"] style:UIBarButtonItemStylePlain target:self action:@selector(backAction)];
    
    
    UIColor *color = RGB(51, 51, 51);
    self.navigationController.navigationBar.tintColor = color;

    NSDictionary *dict = [NSDictionary dictionaryWithObject:color forKey:NSForegroundColorAttributeName];
    self.navigationController.navigationBar.titleTextAttributes = dict;
    
    [self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"title"]) {
        if (object == self.webView) {
            self.title = self.webView.title;
        } else {
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

- (void)dealloc {
    [self.webView removeObserver:self forKeyPath:@"title"];
}

- (void)backAction{
//    [self.navigationController popToViewController:self.navigationController.viewControllers.firstObject animated:YES];
    if (self.webView.canGoBack) {
        [self.webView goBack];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if (_isFirstAppear) {
        _isFirstAppear = NO;
        return;
    }
}

- (void)viewWillAppear:(BOOL)animated {
//    [self.navigationController setNavigationBarHidden:!_hasNavigation animated:animated];
    self.navigationController.navigationBar.hidden = !_hasNavigation;
    
    if (self.hasNavigation) {
        self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    }
    
    [super viewWillAppear:animated];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - WKHandleCallBack
- (void)callURLApp:(NSDictionary *)params{
    
    NSURL *appURL = FormatURL(@"%@",params[@"url"]);
    
    if ([appURL.scheme isEqualToString:@"tel"])
    {
        if ([UIDevice currentDevice].systemVersion.floatValue < 10.0) {
            [UIAlert(UIAlertControllerStyleAlert)
             .message(Format(@"%@",[appURL resourceSpecifier]))
             .button(@"取消")
             .button(@"呼叫").onTappedCall(@selector(openURL:)).byParam(appURL)
             presentWith:self];
        } else {
            [self appOpenURL:appURL];
        }
        
        return;
    }else{
    
        [self appOpenURL:appURL];
    }

}

- (void)appOpenURL:(NSDictionary *)param {
    UIApplication *app = [UIApplication sharedApplication];
    NSURL *url = [NSURL URLWithString:param[@"url"]];
    
    if ([app canOpenURL:url])
    {
        [app openURL:url];
    }
}


//返回App
- (void)onJavaScriptBackApp:(id)obj{
    
    //返回是是否刷新
    if (obj != nil) {
        self.backNeedRefresh = [obj[@"isrefresh"] integerValue] == 1 ;
    }
    [self.navigationController popViewControllerAnimated:YES];
}



- (void)onOpenPayPanel:(NSDictionary *)params {
   
}

-(void)onOpenPayZNBKPanel:(NSDictionary *)params {
    [self.parentViewController performSelector:@selector(onOpenPayZNBKPanel:) withObject:params];
}

-(void)onGoAction:(NSDictionary *)params {
    [self.parentViewController performSelector:@selector(onGoAction:) withObject:params];
}

//注册成功
- (void)registSuccessAction:(NSDictionary *)params{                            
  
 

}
- (void)toastNoticeAction:(NSDictionary *)params{
    
    [Toast.makeText(Format(@"%@",params[@"s"])) showOnDismiss:nil];
}
//打开客服功能
- (void)openKFAction:(NSDictionary *)params{
   
}

- (void)sendCodeAction:(NSDictionary *)param{
    
 
}

//0元刷新功能
- (void)refreshAction{

}

//回到主页
- (void)goHomeAction{
    //先处理属性，后做动画处理
    self.tabBarController.selectedIndex = 0;
    [self.navigationController popToRootViewControllerAnimated:YES];
}

#pragma mark - WKDelegate

-(NSArray<WKWebHandle *> *)createWebViewHandles {
    
    // 普通支付
    WKWebHandle *pay = [[WKWebHandle alloc] initWithName:@"pay" Target:self Action:@selector(onOpenPayPanel:)];
    
    // 专家讲座
    WKWebHandle *zjjz = [[WKWebHandle alloc] initWithName:@"payZJJZ" Target:self Action:@selector(onOpenPayPanel:)];
    
    // 智能报考
    WKWebHandle *znbk = [[WKWebHandle alloc] initWithName:@"payZNBK" Target:self Action:@selector(onOpenPayZNBKPanel:)];

    // 打开URL
    WKWebHandle *callURL = [[WKWebHandle alloc] initWithName:@"callURL" Target:self Action:@selector(appOpenURL:)];
    
    // 标签跳转
    WKWebHandle *goAction = [[WKWebHandle alloc] initWithName:@"goAction" Target:self Action:@selector(onGoAction:)];
    
    //注册成功
    WKWebHandle *registSuccess = [[WKWebHandle alloc] initWithName:@"registSuccess" Target:self Action:@selector(registSuccessAction:)];
    
    //toast提醒
    WKWebHandle *toastNotice = [[WKWebHandle alloc] initWithName:@"toastNotice" Target:self Action:@selector(toastNoticeAction:)];
    
    //打开客服
    WKWebHandle *openKF = [[WKWebHandle alloc] initWithName:@"openKF" Target:self Action:@selector(openKFAction:)];
    
    //打开App
    WKWebHandle *callURLApp = [[WKWebHandle alloc]initWithName:@"callURLApp" Target:self Action:@selector(callURLApp:)];
    
    //发送code
    WKWebHandle *sendCode = [[WKWebHandle alloc]initWithName:@"sendCode" Target:self Action:@selector(sendCodeAction:)];

    //0元开通刷新
    WKWebHandle *refresh = [[WKWebHandle alloc]initWithName:@"vippaysuccess" Target:self Action:@selector(refreshAction)];
    
    //返回主页
    WKWebHandle *goHome = [[WKWebHandle alloc]initWithName:@"gohome" Target:self Action:@selector(goHomeAction)];
    
    return @[pay,znbk,zjjz,callURL,goAction,registSuccess,toastNotice,openKF,callURLApp,sendCode,refresh,goHome];
}

- (NSArray<WKUserScript *> *)createUserScripts {
    
    NSURL *path = [[NSBundle mainBundle] URLForResource:@"TWWebAPI" withExtension:@"js"];
    NSString *baseAPI = [NSString stringWithContentsOfURL:path encoding:NSUTF8StringEncoding error:nil];
    WKUserScript *apiScript = [[WKUserScript alloc] initWithSource:baseAPI injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
    
    return @[apiScript];
}

#pragma mark - WKUIDelegate
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
{

   
}

- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler {
    
   
}

#pragma mark - WKNavigationDelegate

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    
}
- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error{
   
   
    if (error.code == -999) return;
    NSURL *url = error.userInfo[@"NSErrorFailingURLKey"];
    [UIAlert(UIAlertControllerStyleAlert).title(@"加载失败").message(error.domain)
     .button(@"重试").style(UIAlertActionStyleDefault).onTappedCall(@selector(loadURL:)).byParam(url)
     .button(@"取消").style(UIAlertActionStyleCancel)
     presentWith:self];
}


- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
  

    NSURL *url = webView.URL;
    
    if ([url.absoluteString hasSuffix:@"/phone/navigate.shtml"] ||
        [url.absoluteString hasSuffix:@"/phone/web.shtml"] ||
        [url.absoluteString containsString:@"/phone/navigate!"]) {
    }
    
    
//    [webView evaluateJavaScript:@"Android.callUrl('http://www.baidu.com')" completionHandler:nil];
    
//    [webView evaluateJavaScript:@"Android.refresh()" completionHandler:nil];
    
//    [webView evaluateJavaScript:@"Android.signsuccess('13843011020','123456')" completionHandler:nil];
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    
    NSURL *url = navigationAction.request.URL;
    
    if (webView.configuration.strongTag) {
        NSRegularExpression *regular = [NSRegularExpression regularExpressionWithPattern:webView.configuration.strongTag options:NSRegularExpressionCaseInsensitive error:nil];

        if ([regular firstMatchInString:url.absoluteString options:0 range:NSMakeRange(0, url.absoluteString.length)].range.location != NSNotFound) {
            decisionHandler(WKNavigationActionPolicyCancel);

            print(@"%@",url);
            [Toast.makeText(@"出了点小问题，即将退出报考指南").autoDismissLaterThan(2)
             showOnDismiss:^{
                 [self.navigationController popViewControllerAnimated:YES];
             }];
            return;
        }
    }
    
    decisionHandler(WKNavigationActionPolicyAllow);
}

#pragma mark - 弹出支付窗口

- (void)PayUI:(NSDictionary *)dic andUrl:(NSString *)url
{
    
}


@end
